<script lang="ts" setup>
import type {
  ActionClickParams,
  InventoryQueryParams as InventorySearchParams,
} from './types';

import { onMounted, onUnmounted, reactive, ref } from 'vue';

import { Card, message, Grid } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

import { BasicForm, useForm } from 'ant-design-vue';

import { Page } from '@vben/common-ui';

import { usePermission } from '#/hooks/permission';
import { $t } from '#/locales';
import { formatTime } from '#/utils/dateUtil';

import { useColumns, useGridFormSchema } from './data';
import { InventoryAdjustModal } from './modules/AdjustModal';
import { InventoryDetailModal } from './modules/DetailModal';
import { InventoryMoveModal } from './modules/MoveModal';
import { exportInventoryData, getInventoryList } from './services';

// 权限检查
const { hasPermission } = usePermission();

// 搜索表单
const searchFormSchema = useGridFormSchema();
const [
  registerSearchForm,
  { resetFields: resetSearchForm, getFieldsValue: getSearchFormValues },
] = useForm({
  schema: searchFormSchema,
  layout: 'horizontal',
  showActionButtonGroup: false,
  baseColProps: {
    xl: 8,
    lg: 8,
    md: 12,
    sm: 24,
    xs: 24,
  },
});

// 搜索表单数据
const searchFormData = reactive<InventorySearchParams>({
  product_code: '',
  product_name: '',
  specification: '',
  warehouse_id: undefined,
  location_id: undefined,
  status: undefined,
  page_size: 20,
  page_num: 1,
});

// 库存列表数据
const inventoryList = ref<any[]>([]);
const totalCount = ref(0);

// 表格列配置
const columns = useColumns();

// 模态框实例
defineExpose({
  detailModal,
  adjustModal,
  moveModal,
});
const detailModal = ref<InstanceType<typeof InventoryDetailModal>>();
const adjustModal = ref<InstanceType<typeof InventoryAdjustModal>>();
const moveModal = ref<InstanceType<typeof InventoryMoveModal>>();

/**
 * 创建表格实例
 */
const [registerGrid] = useVbenVxeGrid({
  columns,
  dataSource: inventoryList,
  rowKey: 'inventory_id',
  loading: false,
  pagination: {
    total: totalCount,
    pageSize: 20,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => $t('common.total', { total }),
    pageSizeOptions: ['10', '20', '50', '100'],
  },
  toolbarConfig: {
    enabled: false,
  },
  pagerConfig: {
    pageSizes: [10, 20, 50, 100],
  },
  onPageChange: ({ current, pageSize }) => {
    searchFormData.page_num = current;
    searchFormData.page_size = pageSize;
    loadInventoryData();
  },
});

/**
 * 搜索表单值变化处理
 */
function onSearchFormValuesChange(values: any) {
  Object.assign(searchFormData, values);
}

/**
 * 搜索处理
 */
function onSearch(): void {
  loadInventoryData();
}

/**
 * 重置搜索表单
 */
function onReset(): void {
  resetSearchForm();
  Object.keys(searchFormData).forEach((key) => {
    searchFormData[key as keyof InventorySearchParams] = undefined as any;
  });
  searchFormData.page_size = 20;
  searchFormData.page_num = 1;
  loadInventoryData();
}

/**
 * 加载库存数据
 */
async function loadInventoryData(): Promise<void> {
  try {
    const params = { ...searchFormData };
    const result = await getInventoryList(params);
    inventoryList.value = result.data || [];
    totalCount.value = result.total || 0;
  } catch (error) {
    message.error(error?.message || $t('inventory.loadFailed'));
  }
}

/**
 * 查看详情
 */
function handleViewDetail(record: any): void {
  detailModal.value?.openModal(record);
}

/**
 * 调整库存
 */
function handleAdjustInventory(record: any): void {
  adjustModal.value?.openModal(record);
}

/**
 * 移动库存
 */
function handleMoveInventory(record: any): void {
  moveModal.value?.openModal(record);
}

/**
 * 导出库存数据
 */
async function handleExport(): Promise<void> {
  try {
    message.loading($t('inventory.exporting'));
    const params = { ...searchFormData, page_size: 1000 };
    const result = await exportInventoryData(params);
    if (result instanceof Blob) {
      const url = window.URL.createObjectURL(result);
      const link = document.createElement('a');
      link.href = url;
      link.download = `inventory_${formatTime(new Date(), 'YYYYMMDDHHmmss')}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);
      message.success($t('inventory.exportSuccess'));
    } else {
      message.success($t('inventory.exportSuccess'));
    }
  } catch (error) {
    message.error(error?.message || $t('inventory.exportFailed'));
  }
}

/**
 * 表格操作按钮回调
 */
function onActionClick(params: ActionClickParams): void {
  const { action, record } = params;
  switch (action) {
    case 'adjust':
      handleAdjustInventory(record);
      break;
    case 'move':
      handleMoveInventory(record);
      break;
    case 'view':
      handleViewDetail(record);
      break;
    default:
      break;
  }
}

/**
 * 处理模态框成功事件
 */
function handleModalSuccess(): void {
  loadInventoryData();
}

// 监听自定义事件，刷新表格数据
const handleInventoryUpdated = (): void => {
  loadInventoryData();
};

// 初始化数据
onMounted(() => {
  loadInventoryData();
  window.addEventListener('inventory-adjusted', handleInventoryUpdated);
  window.addEventListener('inventory-moved', handleInventoryUpdated);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('inventory-adjusted', handleInventoryUpdated);
  window.removeEventListener('inventory-moved', handleInventoryUpdated);
});
</script>

<template>
  <Page>
    <template #header>
      <div class="header-wrapper">
        <div class="header-title">
          <span class="text-lg font-semibold text-gray-900">
            {{ $t('inventory.title') }}
          </span>
        </div>
      </div>
    </template>

    <Card class="mb-4">
      <template #extra>
        <div class="flex items-center justify-end gap-2">
          <a-button type="primary" @click="handleExport">
            <icon icon="icon-park-outline:export" class="mr-2" />
            {{ $t('common.export') }}
          </a-button>
        </div>
      </template>

      <BasicForm
        :model="searchFormData"
        :schema="searchFormSchema"
        :label-width="100"
        @register="registerSearchForm"
        @values-change="onSearchFormValuesChange"
      >
        <template #button-group>
          <a-button type="primary" @click="onSearch">
            {{ $t('common.search') }}
          </a-button>
          <a-button @click="onReset">
            {{ $t('common.reset') }}
          </a-button>
        </template>
      </BasicForm>
    </Card>

    <Card>
      <Grid @register="registerGrid" />
    </Card>
  </Page>
</template>

<style lang="less" scoped>
.header-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.header-title {
  display: flex;
  align-items: center;
}

.icon {
  display: inline-block;
  width: 16px;
  height: 16px;
}
</style>
